"""
@release: fsray-api-alpha
@file: user.py
@author: lingdubing
@desc: 操作用户行为的接口层
@character: utf-8
"""

from fastapi import  APIRouter,Depends
from service.UserService import UserService
from service.UserRoleLinkService import UserRoleService
from service.RoleService import RoleService
from models.models import User
from schemas.response import *
from schemas.user_schemas import RegisterModel,LoginModel, UpdatePasswordModel, UserPaingtionModel
from database.redis import code_cache
from core.Utils import generate_code, send_code, check_password
from config import settings
from core.Auth import generate_token,check_permission

router = APIRouter()

@router.get("/check",summary="用户存在检查", response_model=ReturnNoneDataModel)
async def check_user(username: str):
    """
    检查用户是否存在
    :param username:
    :return:
    """

    user_service = UserService()
    user = user_service.get_user_by_username(username)
    user_service.close()

    if user:
        return ReturnNoneDataModel(code=200, message="查询成功，用户已注册", success=True)
    else:
        return ReturnNoneDataModel(code=200, message="查询成功，用户未注册", success=False)


@router.get("/getcode", summary="用户获取验证码", response_model=ReturnNoneDataModel)
async def get_code(username: str):
    """
    获取验证码
    :param username: 用户名
    :return: 验证码
    """
    code_cache_instance: Redis = await code_cache()

    code = generate_code()
    # 设置redis存在时长为90秒
    await code_cache_instance.set(username, code)
    await code_cache_instance.expire(username, 90)
    # 发送短信的函数
    result = send_code(username, code)
    if str(result) == "0":
        return ReturnNoneDataModel(code=STATUS_CODE["success"], message="验证码发送成功", success=True)
    else:
        exp = settings.MSGSTATUSSTR[str(result)]
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message=f"验证码发送失败,异常在{exp}", success=False)


@router.post('/register', summary="用户注册", response_model=ReturnNoneDataModel)
async def register(user: RegisterModel):
    """
    用户注册
    :param user:
    :return:
    """

    # 查询redis数据库里是否存在该用户名的验证码并验证
    code_cache_instance: Redis = await code_cache()
    if not await code_cache_instance.exists(user.username):
        return ReturnNoneDataModel(code=STATUS_CODE["warning"], message="验证码已过期", success=False)
    redis_code = await code_cache_instance.get(user.username)
    if redis_code != user.ver_code:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message="验证码错误", success=False)
    # 删除redis数据库里该用户名的验证码
    await code_cache_instance.delete(user.username)

    user_service = UserService()

    # 查询数据库中是否存在该用户名
    existing_user = user_service.get_user_by_username(user.username)
    if existing_user:
        return ReturnNoneDataModel(code=STATUS_CODE["warning"], message="该账号已注册过", success=True)

    # 创建新用户
    new_user = user_service.create_user(user.username, user.password)
    user_service.close()

    # 给新用户分配一个普通用户的角色
    user_role_service = UserRoleService()
    default_role_id = settings.ROLE_DICT["user"]
    user_role_service.assign_role_to_user(new_user.user_id, default_role_id)
    user_role_service.close()

    return ReturnNoneDataModel(code=STATUS_CODE["success"], message="注册成功", success=True)


@router.post('/login', summary="用户登录", response_model=ReturnTokenModel)
async def login(user: LoginModel):
    """
    用户登录
    :param user:
    :return:
    """

    # 创建 UserService 实例
    user_service = UserService()

    # 查询数据库中是否存在该用户名
    user_info = user_service.get_user_by_username(user.username)
    if user_info is None or user_info.user_status == 0:
        user_service.close()
        return ReturnTokenModel(code=STATUS_CODE["error"], message="该账号密码错误或已被禁用",
                                   success=False,token=None)

    # 处理验证码验证
    cache: Redis = await code_cache()
    if user.ver_code is not None:
        if not await cache.exists(user.username):
            return ReturnTokenModel(code=STATUS_CODE["warning"], message="验证码已过期", success=False, token=None)
        redis_code = await cache.get(user.username)
        if redis_code != user.ver_code:
            return ReturnTokenModel(code=STATUS_CODE["error"], message="验证码错误", success=False, token=None)

        # 验证通过后生成 token
        token = generate_token(user.username)
        await cache.delete(user.username)  # 删除验证码
        return ReturnTokenModel(code=STATUS_CODE["success"], message="登录成功", success=True,token=token)

    # 处理密码验证
    if user.password is not None:
        password_valid = check_password(user.password, user_info.password)
        if password_valid:
            # 密码验证通过，生成 token
            token = generate_token(user.username)
            return ReturnTokenModel(code=STATUS_CODE["success"], message="登录成功", success=True,token=token)
        else:
            return ReturnTokenModel(code=STATUS_CODE["error"], message="账号密码错误或已被禁用",
                                       success=False,token=token)


@router.post("/updatepsw", summary="更改用户密码", response_model=ReturnNoneDataModel)
async def update_usr(user: RegisterModel):
    """
    更改用户密码
    :return:
    """
    # 查询redis数据库里是否存在该用户名的验证码并验证
    cache: Redis = await code_cache()
    if not await cache.exists(user.username):
        return ReturnNoneDataModel(code=STATUS_CODE["warning"], message="验证码已过期", success=False)

    redis_code = await cache.get(user.username)
    if redis_code != user.ver_code:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message="验证码错误", success=False)

    # 删除redis数据库里该用户名的验证码
    await cache.delete(user.username)

    # 创建 UserService 实例
    user_service = UserService()

    # 调用 UserService 更新密码
    password_updated = user_service.update_password_by_username(user.username, user.password)
    user_service.close()

    if password_updated:
        return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改密码成功", success=True)
    else:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message="该用户不存在", success=False)


@router.get("/update_user_status", summary="更改用户状态", response_model=ReturnNoneDataModel)
async def update_user_status(user_id: str):
    """
    更改用户启用禁用状态
    :param user_id:
    :param user_status:
    :return:
    """

    # 创建 UserService 实例
    user_service = UserService()
    # 调用 UserService 更新用户状态
    user_updated = user_service.update_user_status(user_id)
    user_service.close()
    if user_updated:
        return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改用户状态成功", success=True)
    else:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message="该用户不存在", success=False)

@router.get("/update_user_role", summary="更改用户角色", response_model=ReturnNoneDataModel)
async def update_user_role(user_id: str, role_id: str):
    """
    更改用户角色
    :param user_id:
    :param role_id:
    :return:
    """

    print(role_id)
    # 创建 UserService 实例
    user_role_service = UserRoleService()
    # 调用 UserService 更新用户角色
    user_updated = user_role_service.update_user_role_link(user_id, role_id)
    user_role_service.close()
    if user_updated:
        return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改用户角色成功", success=True)
    else:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message="该用户不存在", success=False)

@router.post("/userlist", summary="获取用户列表", response_model=ReturnDataModel,dependencies=[Depends(check_permission)])
async def get_user_list(query: UserPaingtionModel):
    """
    获取用户列表，并根据状态和角色筛选
    """
    print(query)

    # 创建 UserService 实例
    user_service = UserService()

    # 从 query 中提取参数并传递给 get_user_list 方法
    user_list, total = user_service.get_user_list(
        page=query.page,
        page_size=query.page_size,
        user_status=query.user_status,
        user_id=query.user_id
    )
    print(user_list)

    if total <= 0:
        return ReturnDataModel(code=STATUS_CODE["error"], message="查询用户列表错误", success=False, data=[], total=0)

    # 创建 UserRoleService 实例
    user_role_service = UserRoleService()

    # 如果 role_id 不为空，则获取该角色下的用户
    if query.user_role_id is not None:
        # 获取角色下的用户列表
        role_filtered_user_ids = user_role_service.get_user_by_role(role_id=query.user_role_id)

        # 提取所有符合条件的用户ID
        role_filtered_user_ids = [user_role.user_id for user_role in role_filtered_user_ids]

        # 根据角色过滤用户列表，只保留这些用户
        user_list = [user for user in user_list if user.user_id in role_filtered_user_ids]

    role_service = RoleService()

    # 用来存储最终返回的用户信息列表
    final_user_list = []

    # 遍历用户列表，获取每个用户的角色名称并组合数据
    for var in user_list:
        # 获取用户角色信息，注意从 UserRoleLink 获取角色ID而不是直接从 User 获取
        role_link = user_role_service.get_user_role_link(user_id=var.user_id)
        if role_link:
            role = role_service.get_role_by_role_id(role_link.role_id)
            if role:
                user_dict = {
                    'create_time': var.create_time,
                    'user_id': var.user_id,
                    'username': var.username,
                    'user_status': var.user_status,
                    'role_name': role.role_name
                }
                final_user_list.append(user_dict)

    user_service.close()
    user_role_service.close()
    role_service.close()

    return ReturnDataModel(code=STATUS_CODE["success"], message="获取用户列表成功", success=True, data=final_user_list, total=total)


































